var express = require('express');
var app = express();
var xml2js = require('xml2js')
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');

var mongoose = require('mongoose');
var MONGO_URL = "mongodb://localhost/weixin";
mongoose.connect(MONGO_URL);


var TOKEN = "topxgunTG";
var crypto = require('crypto');
var config = require('./config')
var weixin = {
	access_token:'',
	jsapi_ticket:''
}

var request = require('request');

app.use('/static',express.static(__dirname+'/app/public'))
app.use(bodyParser.urlencoded({ extended: false }));
app.use(favicon(__dirname + '/app/public/img/txg.ico'));

app.set('views','./app/views')

app.engine('.html',require('ejs').renderFile)
app.set('view engine','html')
app.use(bodyParser.json());

app.all('*',function(req,res,next){
	res.header("X-Powered-By",'TOPXGUN MAN');
	res.header("server",'TOPXGUN FCU');

	if ('OPTIONS' == req.method) return res.send(200);
	next();
});

var WeixinRoute = require('./app/routes/weixin');


function reflash(){
request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+config.appid+'&secret='+config.appsecret,function(err,resp,body){

	body =JSON.parse(body)
    weixin.access_token=body.access_token;
    request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+weixin.access_token+'&type=jsapi',function(err,resp,body){
	            body = JSON.parse(body)
	            weixin.jsapi_ticket = body.ticket;
	            
	})

})
}



reflash();

setInterval(reflash,2*60*60*1000);


app.use(function(req,res,next){
	req.weixin = weixin;
	//console.log(req.weixin)
	next();
})

app.use('/',WeixinRoute);

// report

var User = require('./app/models/User');
var Activity = require('./app/models/Activity');
var ActivityUser = require('./app/models/ActivityUser');
var Report = require('./app/models/Report');
var eventproxy = require('eventproxy');

function saveReport(){
	var ep = new eventproxy();
	var event_id = '56ac5e8cc604bda532915a2a';

	ep.all('user_count','activity_count','activityuser_count',function(user_count,activity_count,activityuser_count){
		var _report = new Report();
		_report.event_id = event_id;
		_report.user_count = user_count;
		_report.activity_count = activity_count;
		_report.activityuser_count = activityuser_count;
		_report.create_date = new Date().getTime();
		_report.save(function(err,$report){
			if(err){

			}else{

			}
		})	
	})

	User.distinct('openid',{},function(err,users){
		ep.emit('user_count',users.length);
	})

	Activity.count({event_id:event_id},function(err,activity_count){
		ep.emit('activity_count',activity_count);
	})

	ActivityUser.count({},function(err,activityuser_count){
		ep.emit('activityuser_count',activityuser_count);
	})
}

// setInterval(saveReport,30000);
// report

app.listen('5000',function(err){
	if(err){
	//console.log('sth wrong with it')
	}else{
	
	//console.log('the wechat server is runnning')
}
})
